<template>
  <section id="login" class="py-24 md:py-32" :style="{
    backgroundColor: bgColor,
    '--primary-color': primaryColor
  }">
    <div class="container mx-auto px-4 sm:px-6 lg:px-8">
      <div class="max-w-md mx-auto">
        <!-- 标题区域 -->
        <div class="text-center mb-10" v-if="showHeader">
          <span class="text-primary font-medium">用户登录</span>
          <h2 class="text-[clamp(1.75rem,4vw,2.5rem)] font-bold mb-4">欢迎回来</h2>
          <p class="text-gray-600">请登录您的账户以获取更多服务</p>
        </div>

        <!-- 登录表单 -->
        <div class="bg-light rounded-xl p-8 shadow-md transition-all duration-300"
          :style="{ borderRadius: `${formRadius}px` }">
          <form @submit.prevent="handleLogin">
            <!-- 邮箱输入 -->
            <div class="mb-6">
              <label :for="`${idPrefix}-email`" class="block text-gray-800 mb-2 text-sm font-medium">
                邮箱
                <span v-if="fields.email.required" class="text-red-500">*</span>
              </label>
              <input type="email" :id="`${idPrefix}-email`"
                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom"
                placeholder="您的邮箱地址" v-model="formData.email" :required="fields.email.required"
                :disabled="isSubmitting">
              <p v-if="errors.email" class="text-red-500 text-sm mt-1">{{ errors.email }}</p>
            </div>

            <!-- 密码输入 -->
            <div class="mb-6">
              <div class="flex justify-between mb-2">
                <label :for="`${idPrefix}-password`" class="block text-gray-800 text-sm font-medium">
                  密码
                  <span v-if="fields.password.required" class="text-red-500">*</span>
                </label>
                <a href="#" class="text-primary text-sm hover:underline transition-all duration-300"
                  @click.prevent="handleForgotPassword" :disabled="isSubmitting">
                  忘记密码？
                </a>
              </div>
              <div class="relative">
                <input :type="showPassword ? 'text' : 'password'" :id="`${idPrefix}-password`"
                  class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-custom"
                  placeholder="您的密码" v-model="formData.password" :required="fields.password.required"
                  :disabled="isSubmitting">
                <button type="button"
                  class="absolute right-3 top-1/2 -translate-y-1/2 text-dark/50 hover:text:translate-y-0"
                  style="position: absolute; transform: translateY(-50%); right: 12px;" @click="toggleShowPassword"
                  :disabled="isSubmitting">
                  <i class="fa" :class="showPassword ? 'fa-eye-slash' : 'fa-eye'"></i>
                </button>
                <p v-if="errors.password" class="text-red-500 text-sm mt-1">{{ errors.password }}</p>
              </div>
            </div>

            <!-- 记住我选项 -->
            <div class="mb-6" v-if="showRememberMe">
              <label class="flex items-center">
                <input type="checkbox" class="w-4 h-4 text-primary rounded border-gray-300 focus:ring-primary"
                  v-model="formData.rememberMe" :disabled="isSubmitting">
                <span class="ml-2 text-gray-600">记住我 30 天</span>
              </label>
            </div>

            <!-- 登录按钮 -->
            <button type="submit"
              class="w-full py-3 bg-primary text-white rounded-lg hover:bg-primary/90 transition-all duration-300 mb-6 hover:opacity-90"
              :disabled="isSubmitting">
              <span v-if="!isSubmitting">登录</span>
              <span v-if="isSubmitting">
                <i class="fa fa-spinner fa-spin mr-2"></i>登录中...
              </span>
            </button>

            <!-- 其他登录方式 -->
            <div class="text-center mb-6" v-if="socialLoginOptions.length > 0">
              <p class="text-gray-600">或者使用以下方式登录</p>

              <div class="flex justify-center space-x-4 mt-4">
                <a href="#" v-for="(option, index) in socialLoginOptions" :key="index"
                  :class="`w-12 h-12 rounded-full ${option.bgColor}/10 flex items-center justify-center ${option.textColor} hover:${option.bgColor} hover:text-white transition-all duration-300`"
                  @click.prevent="handleSocialLogin(option.provider)" :disabled="isSubmitting" :title="option.label">
                  <i :class="`fa ${option.icon} text-xl`"></i>
                </a>
              </div>
            </div>

            <!-- 注册入口 -->
            <p class="text-center text-gray-600" v-if="showRegisterLink">
              还没有账户？ <a href="#" class="text-primary font-medium hover:underline transition-all duration-300"
                @click.prevent="handleRegisterClick">
                立即注册
              </a>
            </p>
          </form>

          <!-- 登录结果提示 -->
          <div v-if="loginStatus" class="mt-4 p-3 rounded-lg text-sm" :class="{
            'bg-green-50 text-green-700': loginStatus === 'success',
            'bg-red-50 text-red-700': loginStatus === 'error'
          }">
            <p v-if="loginStatus === 'success'">
              <i class="fa fa-check-circle mr-1"></i>登录成功，正在跳转...
            </p>
            <p v-if="loginStatus === 'error'">
              <i class="fa fa-exclamation-circle mr-1"></i>登录失败：{{ errorMessage }}
            </p>
          </div>
        </div>
      </div>
    </div>
  </section>
</template>

<script>
export default {
  name: 'LoginSection',
  // 低代码平台元数据
  lowcode: {
    meta: {
      name: 'login-section',
      displayName: '用户登录模块',
      description: '用于用户登录的表单组件，支持邮箱密码登录和第三方登录',
      icon: 'fa-key',
      category: '用户组件',
      version: '1.0.0',
      isContainer: false
    },

    configPanel: [
      {
        title: '基本配置',
        fields: [
          {
            name: 'primaryColor',
            label: '主题色',
            type: 'color',
            defaultValue: '#165DFF'
          },
          {
            name: 'bgColor',
            label: '背景色',
            type: 'color',
            defaultValue: '#ffffff'
          },
          {
            name: 'showHeader',
            label: '显示标题区域',
            type: 'boolean',
            defaultValue: true
          }
        ]
      },
      {
        title: '表单配置',
        fields: [
          {
            name: 'formRadius',
            label: '表单圆角',
            type: 'number',
            min: 0,
            max: 20,
            defaultValue: 8
          },
          {
            name: 'idPrefix',
            label: 'ID前缀',
            type: 'text',
            defaultValue: 'login',
            description: '用于表单元素ID的前缀，避免重复'
          },
          {
            name: 'showRememberMe',
            label: '显示记住我选项',
            type: 'boolean',
            defaultValue: true
          },
          {
            name: 'showRegisterLink',
            label: '显示注册链接',
            type: 'boolean',
            defaultValue: true
          }
        ]
      },
      {
        title: '字段配置',
        fields: [
          {
            name: 'fields',
            label: '字段设置',
            type: 'object',
            description: '配置各字段是否必填',
            defaultValue: {
              email: { required: true },
              password: { required: true }
            }
          }
        ]
      },
      {
        title: '第三方登录配置',
        fields: [
          {
            name: 'socialLoginOptions',
            label: '第三方登录选项',
            type: 'array',
            description: '配置支持的第三方登录方式',
            defaultValue: [
              {
                provider: 'weixin',
                label: '微信登录',
                icon: 'fa-weixin',
                bgColor: '#07C160',
                textColor: '#07C160'
              },
              {
                provider: 'qq',
                label: 'QQ登录',
                icon: 'fa-qq',
                bgColor: '#1DA1F2',
                textColor: '#1DA1F2'
              },
              {
                provider: 'weibo',
                label: '微博登录',
                icon: 'fa-weibo',
                bgColor: '#E4405F',
                textColor: '#E4405F'
              }
            ]
          }
        ]
      }
    ],

    events: [
      {
        name: 'login',
        label: '登录提交',
        description: '用户提交登录表单时触发',
        parameters: [
          { name: 'formData', type: 'object', description: '登录表单数据' }
        ]
      },
      {
        name: 'loginSuccess',
        label: '登录成功',
        description: '用户登录成功后触发',
        parameters: [
          { name: 'user', type: 'object', description: '用户信息' }
        ]
      },
      {
        name: 'loginError',
        label: '登录失败',
        description: '用户登录失败时触发',
        parameters: [
          { name: 'error', type: 'object', description: '错误信息' }
        ]
      },
      {
        name: 'socialLogin',
        label: '第三方登录',
        description: '用户点击第三方登录时触发',
        parameters: [
          { name: 'provider', type: 'string', description: '第三方平台标识' }
        ]
      },
      {
        name: 'forgotPassword',
        label: '忘记密码',
        description: '用户点击忘记密码链接时触发'
      },
      {
        name: 'register',
        label: '注册账号',
        description: '用户点击注册链接时触发'
      }
    ],

    actions: [
      {
        name: 'resetForm',
        label: '重置表单',
        description: '清空登录表单内容'
      },
      {
        name: 'login',
        label: '执行登录',
        description: '手动触发登录操作',
        parameters: [
          { name: 'credentials', type: 'object', required: true, description: '登录凭证，包含email和password' }
        ]
      }
    ]
  },

  props: {
    // 颜色配置
    primaryColor: {
      type: String,
      default: '#165DFF'
    },
    bgColor: {
      type: String,
      default: '#ffffff'
    },

    children: {
      type: Array,
      default: () => []
    },
    // 表单配置
    formRadius: {
      type: Number,
      default: 8,
      validator: (value) => value >= 0 && value <= 20
    },
    idPrefix: {
      type: String,
      default: 'login'
    },
    showHeader: {
      type: Boolean,
      default: true
    },
    showRememberMe: {
      type: Boolean,
      default: true
    },
    showRegisterLink: {
      type: Boolean,
      default: true
    },

    // 字段配置
    fields: {
      type: Object,
      default: () => ({
        email: { required: true },
        password: { required: true }
      })
    },

    // 第三方登录配置
    socialLoginOptions: {
      type: Array,
      default: () => [
        {
          provider: 'weixin',
          label: '微信登录',
          icon: 'fa-weixin',
          bgColor: '#07C160',
          textColor: '#07C160'
        },
        {
          provider: 'qq',
          label: 'QQ登录',
          icon: 'fa-qq',
          bgColor: '#1DA1F2',
          textColor: '#1DA1F2'
        },
        {
          provider: 'weibo',
          label: '微博登录',
          icon: 'fa-weibo',
          bgColor: '#E4405F',
          textColor: '#E4405F'
        }
      ]
    }
  },

  data() {
    return {
      // 表单数据
      formData: {
        email: '',
        password: '',
        rememberMe: false
      },
      // 显示密码切换
      showPassword: false,
      // 提交状态
      isSubmitting: false,
      loginStatus: null, // null, 'success', 'error'
      errorMessage: '',
      // 表单验证错误
      errors: {}
    };
  },

  computed: {},

  watch: {},

  methods: {
    /**
     * 验证表单
     */
    validateForm() {
      const errors = {};
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

      // 验证邮箱
      if (this.fields.email.required && !this.formData.email.trim()) {
        errors.email = '请输入邮箱地址';
      } else if (this.formData.email.trim() && !emailRegex.test(this.formData.email.trim())) {
        errors.email = '请输入有效的邮箱地址';
      }

      // 验证密码
      if (this.fields.password.required && !this.formData.password.trim()) {
        errors.password = '请输入密码';
      }

      this.errors = errors;
      return Object.keys(errors).length === 0;
    },

    /**
     * 处理登录提交
     */
    handleLogin() {
      // 表单验证
      if (!this.validateForm()) {
        return;
      }

      this.isSubmitting = true;
      this.loginStatus = null;
      this.errorMessage = '';

      // 触发登录事件
      this.$emit('login', this.formData);

      // 模拟API登录
      setTimeout(() => {
        // 实际项目中这里会调用登录API
        const success = true; // 模拟成功/失败

        if (success) {
          this.loginStatus = 'success';
          // 模拟用户信息
          const userInfo = {
            email: this.formData.email,
            name: '用户名称',
            token: 'dummy-token-123456'
          };
          this.$emit('loginSuccess', userInfo);

          // 登录成功后跳转（实际项目中会跳转到首页或之前的页面）
          setTimeout(() => {
            this.$emit('loginRedirect', userInfo);
          }, 1500);
        } else {
          this.loginStatus = 'error';
          this.errorMessage = '邮箱或密码不正确';
          this.$emit('loginError', { message: this.errorMessage });
        }

        this.isSubmitting = false;
      }, 1500);
    },

    /**
     * 切换密码显示状态
     */
    toggleShowPassword() {
      this.showPassword = !this.showPassword;
    },

    /**
     * 处理忘记密码
     */
    handleForgotPassword() {
      this.$emit('forgotPassword');
    },

    /**
     * 处理注册点击
     */
    handleRegisterClick() {
      this.$emit('register');
    },

    /**
     * 处理第三方登录
     */
    handleSocialLogin(provider) {
      this.$emit('socialLogin', provider);
      // 实际项目中这里会调用对应第三方平台的登录SDK
    },

    /**
     * 重置表单
     */
    resetForm() {
      this.formData = {
        email: '',
        password: '',
        rememberMe: false
      };
      this.showPassword = false;
      this.errors = {};
      this.loginStatus = null;
      this.errorMessage = '';
    },

    /**
     * 手动执行登录
     */
    login(credentials) {
      if (credentials && credentials.email && credentials.password) {
        this.formData.email = credentials.email;
        this.formData.password = credentials.password;
        this.handleLogin();
      }
    }
  }
};
</script>

<style scoped>
/* 已替换为Tailwind CSS样式 */
</style>